#include "utils/rabbitmq_client.hpp"
#include <iostream>

RabbitMQClient::RabbitMQClient(const std::string& uri, const std::string& exchange, const std::string& queue, const std::string& routingkey)
    : m_exchange(exchange)
    , m_queue(queue)
    , m_routingKey(routingkey) {
    try {
        m_channel = AmqpClient::Channel::CreateFromUri(uri);
        m_channel->DeclareExchange(m_exchange, AmqpClient::Channel::EXCHANGE_TYPE_FANOUT, false, true); 
        m_channel->DeclareQueue(m_queue, false, true, false, false);
        m_channel->BindQueue(m_queue, m_exchange, m_routingKey);
    } catch (const std::exception& e) {
        std::cerr << "RabbitMQ Client Error: " << e.what() << std::endl;
        m_channel = nullptr;
    }
}


RabbitMQClient::~RabbitMQClient() {}


bool RabbitMQClient::publish(const std::string& message) {
    if (!m_channel) return false;
    try {
        m_channel->BasicPublish(m_exchange, m_routingKey, AmqpClient::BasicMessage::Create(message));
        return true;
    }  catch (const std::exception& e) {
        std::cerr << "RabbitMQ Publish Error: " << e.what() << std::endl; 
        return false;
    }
}


std::string RabbitMQClient::consume() {
    if (!m_channel) return "";
    try {
        AmqpClient::Envelope::ptr_t envelope;
        if (m_channel->BasicGet(envelope, m_queue, true)) {
            return envelope->Message()->Body();
        }
    } catch (const std::exception& e) {
        std::cerr << "RabbitMQ Consume Error: " << e.what() << std::endl;
    }
    return "";
}
 
